import { Button, IndexBar, List, SearchBar, Space } from "antd-mobile";
import withLogin from "../../Components/withLogin";
import { useRequest } from "../../hooks/useRequest";
import { useEffect, useState } from "react";
import { request } from "../../utils/request";
import { useNavigate } from "react-router-dom";
import { throttle }  from 'lodash'
const City = () => {
  const { data = { cityList: [], hotCities: [] } } = useRequest("/city", "get");
  const [searchList, setSearchList] = useState([]);
  const [isSearch, setIsSearch] = useState(false);
  const navigate = useNavigate()
  const onSearch = throttle(async (value) => {
    setIsSearch(true);

    const resp = await request.get("/city/search", { params: { wd: value } });
    console.log(resp.data.data);
    setSearchList(resp.data.data);
  }, 400);

  const handleClickCity = city => {
    navigate(-1)
    localStorage.setItem('city', city)
  }



  return (
    <div style={{ height: "100vh", overflow: "hidden" }}>
      <SearchBar
        placeholder="请输入城市"
        onSearch={onSearch}
        onClear={() => {
          setIsSearch(false);
        }}
      ></SearchBar>
      {isSearch ? (
        <div>
          <List>
            {searchList.map((v, i) => {
              return <List.Item key={i} onClick={() => handleClickCity(v.name) }>{v.name}</List.Item>;
            })}
          </List>
        </div>
      ) : (
        <>
          <Space wrap style={{ padding: 20 }}>
            {data.hotCities.map((v, i) => {
              return <Button key={i} onClick={() => handleClickCity(v.name)}>{v.name}</Button>;
            })}
          </Space>

          <IndexBar>
            {data.cityList.map((v, i) => {
              return (
                <IndexBar.Panel key={i} title={v.title} index={v.title}>
                  <List>
                    {v.citys.map((v, i) => {
                      return <List.Item key={i} onClick={() => handleClickCity(v.name)}>{v.name}</List.Item>;
                    })}
                  </List>
                </IndexBar.Panel>
              );
            })}
          </IndexBar>
        </>
      )}
    </div>
  );
};

export default withLogin(City);
